using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using System.ServiceModel;

using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;


namespace TicketSellerService {
	public class VendorServerHost {
        private const int NUMBER_OF_ARGUMENTS = 4;

        private const int VENDOR_NAME = 0;

        private const int SERVER_PORT = 1;

        private const int SEARCH_SERVER_URL = 2;

        private const int FLIGHTS_INPUT_FILE = 3;

		static public void Main( string[] args) {
            if ( args.Length != NUMBER_OF_ARGUMENTS)
            {
                Console.WriteLine( "Error program intput.");
                Console.WriteLine("Expected must parameters: <name> <port> <flight search server> <input file name>");
                return;

            }

            string uri = String.Format("http://localhost:{0}/TicketVendorService", args[SERVER_PORT]);

            try
            {
                Convert.ToInt32(args[SERVER_PORT]);
            }
            catch (InvalidCastException e)
            {
                Console.WriteLine( "Incorrect port number. Exiting...");
                return;
            }

            
            string inputFileName = args[FLIGHTS_INPUT_FILE];

            if ( !File.Exists( inputFileName)) {
                Console.WriteLine( "Could not find flights input file. Exiting...");
                return;
            }
            TicketsDB.getInstance().initialize( inputFileName);
			using( WebServiceHost host = new WebServiceHost( typeof(FlightTicketService), 
			                                         new Uri( uri)) ) {
				
				try {
					host.Open( );
                    using (VendorRegistrationClient proxy = new VendorRegistrationClient("BasicHttpBinding_IVendorRegistration"))
                    {
                        proxy.registerVendor("orbitz", uri);
                    }
                    Console.WriteLine("Host opened connection.");
					Console.ReadLine( );
				} catch (InvalidOperationException e) {
					Console.WriteLine( e.Message.ToString( ));
					Console.WriteLine( e.StackTrace.ToString( )); 
				} finally {
					host.Close( );
				}
			}
		}
	}
}

